<template>
  <div class="gl_contentBox gl_heightFull">
    <div class="gl_my_15 current_mainclub">
      当前主道馆：
      <span class="mainclub_name">{{ parentName }}</span>
      <el-button v-if="canApply" type="primary" size="mini" @click="clickJoin">申请加入</el-button>
    </div>
    <el-tabs v-model="activeTab" class="gl_tabs" type="card" @tab-click="handleClick">
      <el-tab-pane v-for="(item, index) in tabList" :key="index" :label="item.label" :name="item.name">
        <div class="demo-input-suffix gl_searchBox">
          <el-row :gutter="20">
            <el-col :span="4">
              <p>道馆名称</p>
              <el-input v-model="qo.Filter" placeholder="请输入道馆名称" size="mini" clearable @change="getPageList()" />
            </el-col>
            <el-col :span="6">
              <p>申报时间</p>
              <el-date-picker
                v-model="chooseTime"
                size="mini"
                type="daterange"
                style="width:100%"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="handleTimeChange"
              />
            </el-col>
            <el-col :span="4">
              <p>审核结果</p>
              <el-select v-model="selected" size="mini" placeholder="请选择审核结果" filterable @change="getPageList()">
                <el-option label="全部" :value="null" />
                <el-option v-for="jtem in dict.branchRequestStatus" :key="jtem.code" :value="jtem.code" :label="jtem.value" />
              </el-select>
            </el-col>
            <el-col :span="10" class="search_btn">
              <!-- 查询按钮 -->
              <el-button type="primary" size="mini" @click="getPageList()">筛选</el-button>
              <!-- 重置按钮 -->
              <el-button type="warning" size="mini" @click="clickReset()">{{ $t('button.Reset') }}</el-button>
            </el-col>
          </el-row>
        </div>
        <el-table v-loading="tableLoading" :data="tableData" class="gl_table_noBorder gl_mt_15" size="mini" style="width: 100%;">
          <el-table-column label="序号" type="index" width="70" :index="table_index" />
          <el-table-column label="道馆名称" :min-width="120">
            <template slot-scope="{row}">
              {{ activeTab === 'application' ? row.parentDelegation ? row.parentDelegation.name : '' : row.delegation ? row.delegation.name : '' }}
            </template>
          </el-table-column>
          <el-table-column label="所在地区" :min-width="120">
            <template slot-scope="{row}">
              <span v-if="activeTab === 'application' && row.parentDelegation">{{ addressDataForCheck(row.parentDelegation.provinceCode, row.parentDelegation.cityCode, row.parentDelegation.countyCode) }}</span>
              <span v-if="activeTab === 'approval' && row.delegation">{{ addressDataForCheck(row.delegation.provinceCode, row.delegation.cityCode, row.delegation.countyCode) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="联系人" :min-width="120">
            <template slot-scope="{row}">
              {{ activeTab === 'application' ? row.parentDelegation ? row.parentDelegation.contactPerson : '' : row.delegation ? row.delegation.contactPerson : '' }}
            </template>
          </el-table-column>
          <el-table-column label="联系方式">
            <template slot-scope="{row}">
              {{ activeTab === 'application' ? row.parentDelegation ? row.parentDelegation.phoneNumber : '' : row.delegation ? row.delegation.phoneNumber : '' }}
            </template>
          </el-table-column>
          <el-table-column label="审核结果">
            <template slot-scope="{row}">
              <span v-for="jtem in dict.branchRequestStatus" :key="jtem.code">{{ jtem.code === row.branchRequestStatusCode ? jtem.value : '' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="提交时间" :min-width="140">
            <template slot-scope="{row}">
              <span v-if="row.creationTime">
                {{ row.creationTime | FormatDate('yyyy-MM-dd HH:mm:ss') }}
              </span>
            </template>
          </el-table-column>
          <el-table-column v-if="activeTab === 'application'" :label="$t('table.actions')" :min-width="100">
            <template slot-scope="{ row }">
              <el-button v-if="row.branchRequestStatusCode === 'Pending'" size="mini" type="text" @click="cancelApply(row.id)">撤销</el-button>
              <el-button v-else size="mini" type="text" disabled>撤销</el-button>
            </template>
          </el-table-column>
          <el-table-column v-if="activeTab === 'approval'" :label="$t('table.actions')" width="100">
            <template slot-scope="{ row }">
              <el-button size="mini" type="text" :disabled="row.branchRequestStatusCode !== 'Pending'" @click="apply(row.id, true)">通过</el-button>
              <el-button size="mini" type="text" :disabled="row.branchRequestStatusCode !== 'Pending'" @click="apply(row.id, false)">不通过</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row class="gl_pt_15" style="text-align: right;">
          <el-pagination
            :current-page="qo.Page"
            :page-size="qo.MaxResultCount"
            :total="total"
            layout="total,sizes,prev,pager,next,jumper"
            :page-sizes="[10, 20, 30, 40]"
            @size-change="sizeChange"
            @current-change="pageIndexChange"
          />
        </el-row>
      </el-tab-pane>
    </el-tabs>
    <addRequest ref="addRequest" />
  </div>
</template>

<script>
// import { deepCopy } from '@/lib';
import addRequest from './addRequest.vue';
import { mapState, mapActions } from 'vuex';
import {
  Api_GET_ClubBranchQO, // 查询分道馆申请列表
  Api_POST_ClubBranchIdApproveQO // 审核指定申请
} from '@/lib/form/hall/swaggerForm';
import {
  api_POST_ClubBranchCanRequest, // 是否可以申请
  api_GET_ClubBranch, // 查询分道馆申请列表
  api_POST_ClubBranchIdRevoke, // 撤销指定申请
  api_POST_ClubBranchIdApprove, // 审核指定申请
  api_GET_ClubBranchParent // 获取已经加入的父级道馆
} from '@/extend/api/hallswaggerApi/app';
export default {
  components: { addRequest },
  data() {
    return {
      activeTab: '',
      tabList: [
        {
          label: '我的申请',
          name: 'application'
        },
        {
          label: '我的审批',
          name: 'approval'
        }
      ],
      chooseTime: [],
      qo: new Api_GET_ClubBranchQO(),
      tableLoading: false,
      total: 0,
      tableData: [],
      canApply: false,
      selected: null,
      parentName: ''
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      cache: state => state.dict.cache,
      user: state => state.user.currentOU
    })
  },
  created() {
    this.getDict();
    this.init();
  },
  methods: {
    // 若没有字典信息，外部可直接调用方法获取字典数据
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType' }),
    // 初始化
    init() {
      this.canRequest();
      this.parentClub();
      if (this.qo) {
        this.qo.BranchRequestStatusCodes = '';
      }
      // 默认选中申请列表
      this.activeTab = 'application';
      this.qo.OrganizationUnitId = this.user;
      this.qo.IncludeDelegation = false;
      this.qo.IncludeParentDelegation = true;
      this.qo.ParentId = null;
      this.getPageList();
    },
    // 是否可以申请
    canRequest() {
      const that = this;
      api_POST_ClubBranchCanRequest().then(res => {
        that.canApply = res;
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 撤销指定申请
    cancelApply(id) {
      const that = this;
      api_POST_ClubBranchIdRevoke(id).then(res => {
        this.$message({ type: 'success', message: '撤销成功' });
        that.canRequest();
        this.getPageList();
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 审核指定申请
    apply(id, isApproved) {
      const qo = new Api_POST_ClubBranchIdApproveQO();
      qo.isApproved = isApproved;
      api_POST_ClubBranchIdApprove(id, qo).then(res => {
        this.$message({ type: 'success', message: '审核成功' });
        this.getPageList();
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 申请加入
    clickJoin() {
      this.$refs.addRequest.dialogVisible = true;
    },
    // 查询分道馆申请列表
    getPageList(page) {
      this.qo.Page = page || 1;
      this.qo.SkipCount = (this.qo.Page - 1) * this.qo.MaxResultCount;
      this.tableLoading = true;
      this.qo.BranchRequestStatusCodes = this.selected;
      api_GET_ClubBranch(this.qo).then(res => {
        this.tableLoading = false;
        this.tableData = res.items;
        this.total = res.totalCount;
      }, error => {
        this.tableLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 获取已经加入的父级道馆
    parentClub() {
      api_GET_ClubBranchParent().then(res => {
        if (res) {
          this.parentName = res.name;
        }
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 处理省市区
    addressDataForCheck (_provinceCode, _cityCode, _countyCode) {
      let _provinceData;
      let _cityData;
      let _countyData;
      if (_provinceCode && this.cache.district) {
        _provinceData = this.cache.district.find(item => item.code === _provinceCode);
      }
      if (_cityCode && _provinceData) {
        _cityData = _provinceData.children.find(item => item.code === _cityCode);
      }
      if (_countyCode && _cityData) {
        _countyData = _cityData.children.find(item => item.code === _countyCode);
      }
      _provinceData = _provinceData ? _provinceData.name : '';
      _cityData = _cityData ? _cityData.name : '';
      _countyData = _countyData ? _countyData.name : '';
      return `${_provinceData} ${_cityData} ${_countyData}`;
    },
    clickReset() {
      this.qo.Filter = '';
      this.chooseTime = [];
      this.qo.MinCreationTime = '';
      this.qo.MaxCreationTime = '';
      this.selected = null;
      this.getPageList();
    },
    handleTimeChange(time) {
      this.qo.MinCreationTime = time ? time[0] : null;
      this.qo.MaxCreationTime = time ? time[1] : null;
      this.getPageList();
    },
    handleClick(tab) {
      if (tab.name === 'approval') { // 审批
        this.qo.OrganizationUnitId = null;
        this.qo.ParentId = this.user;
        this.qo.IncludeDelegation = true;
        this.qo.IncludeParentDelegation = false;
        // 解决申请与审批时间选择器联动问题
        this.chooseTime = [];
        this.qo.MinCreationTime = '';
        this.qo.MaxCreationTime = '';
      } else { // 申请
        this.qo.OrganizationUnitId = this.user;
        this.qo.ParentId = null;
        this.qo.IncludeDelegation = false;
        this.qo.IncludeParentDelegation = true;
        this.chooseTime = [];
        this.qo.MinCreationTime = '';
        this.qo.MaxCreationTime = '';
      }
      this.getPageList();
    },
    table_index(index) {
      return (this.qo.Page - 1) * this.qo.MaxResultCount + index + 1;
    },
    // 分页
    sizeChange(MaxResultCount) {
      this.qo.MaxResultCount = MaxResultCount;
      this.getPageList();
    },
    pageIndexChange(currentPage) {
      this.getPageList(currentPage);
    }
  }
};
</script>
<style lang="scss" scoped>
.current_mainclub {
  font-size: 16px;
  .mainclub_name {
    font-weight: bold;
    display: inline-block;
    margin-right: 15px;
  }
}
</style>
